package com.github.ybq.core.style;

import com.github.ybq.core.sprite.Sprite;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.render.ThreeDimView;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;

public class RotatingPlane extends Sprite {

//    private static String TAG = "RotatingPlane";

    private AnimatorValue mAnimatorValue;

    private float time = 0f;

    private Path mPath;

    public RotatingPlane() {
        super();
        initAnimator();
        mPath = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setStyle(Paint.Style.FILL_STYLE);
        int saveCount = canvas.save();

        if (getRect() != null) {
            Rect bounds = clipSquare(getRect(),(int) (getRect().getHeight()/4));
            ThreeDimView threeDimView = new ThreeDimView();

            canvas.translate(bounds.getCenterX()  , bounds.getCenterY() );
            if (time > 0.5){
                threeDimView.rotateX((time - 0.5f) * 360);
            }else {
                threeDimView.rotateY(time * 360);
            }
            threeDimView.applyToCanvas(canvas);
            canvas.translate(-bounds.getCenterX() , -bounds.getCenterY()) ;

            canvas.drawRect(new RectFloat(bounds),mPaint);

            startAnimator();
        }
        canvas.restoreToCount(saveCount);
    }
    @Override
    public void startAnimator(){
        if (mAnimatorValue != null) {
            if (!mAnimatorValue.isRunning()) {
                mAnimatorValue.start();
            }
        }else {
            initAnimator();
            if (!mAnimatorValue.isRunning()) {
                mAnimatorValue.start();
            }
        }
    }

    private void initAnimator() {
        if (mAnimatorValue == null) {
            mAnimatorValue = new AnimatorValue();
            mAnimatorValue.setLoopedCount(Animator.INFINITE);
            mAnimatorValue.setDuration(2000);

            mAnimatorValue.setCurveType(Animator.CurveType.LINEAR);
            mAnimatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    time = v;

                    if (getComponent() != null) {
                        getComponent().invalidate();
                    }
                }
            });
        }
    }
    @Override
    public boolean isRunning() {
        if (mAnimatorValue != null){
            return mAnimatorValue.isRunning();
        }
        return super.isRunning();
    }
    @Override
    public void stopAnimator(){
        if (mAnimatorValue != null){
            if (mAnimatorValue.isRunning()){
                mAnimatorValue.stop();
            }
        }
    }
}

